/*
 *  MainWindow.java 
 *    
 *    Copyright 2012 YAWP Project Team
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.googlecode.yawp.view;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.io.IOException;
import java.net.URL;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JLabel;

import com.googlecode.yawp.model.Model;

import javax.swing.ImageIcon;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;

/**
 * Main View Window 
 * 
 * @author ccato
 *
 */
@SuppressWarnings("serial")
public class MainWindow extends JFrame implements Observer, WindowListener {

	private Model model;
	
	private JPanel contentPane;
	private JButton btnClose;
	private JButton btnChangeUser;
	private JButton btnChart;
	private JButton btnEnterWeight;
	private JButton btnPreferences;
	private JLabel lblWelcome;
	private JMenuBar menuBar;
	private JMenu mnFile;
	private JMenuItem mntmExit;
	private JMenu mnHelp;
	private JMenuItem mntmAbout;
	private JMenu mnPreferences;
	private JMenuItem mntmPreferences;
	private JMenu mnChart;
	private JMenuItem mntmChart;
	private JPanel panel_3;
	private JMenuItem mntmChangeUser;

	/**
	 * Launch the application - for stand alone testing only.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainWindow frame = new MainWindow();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Constructor - Create the frame.
	 * @param model
	 */
	public MainWindow(Model model) {
		this.model = model;
		model.addObserver(this);
		initialize();
		update(null, null);
	}

	
	/**
	 * Constructor - Create the frame.
	 */
	public MainWindow() {
		initialize();
	}
	
	/**
	 * Initialize the window
	 */
	public void initialize() {
		setTitle("YAWP - Main Window");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		addWindowListener(this);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.CENTER);
		panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
	
		lblWelcome = new JLabel("Welcome User...");
		panel.add(lblWelcome);
				
		JPanel panel_1 = new JPanel();
		contentPane.add(panel_1, BorderLayout.SOUTH);
		
		btnClose = new JButton("Exit");
		panel_1.add(btnClose);
		
		JPanel panel_2 = new JPanel();
		contentPane.add(panel_2, BorderLayout.WEST);
		panel_2.setLayout(new GridLayout(5, 1, 0, 0));
				
		btnChangeUser = new JButton("Change User");
		panel_2.add(btnChangeUser);
		
		btnChart = new JButton("Chart");
		panel_2.add(btnChart);

		btnEnterWeight = new JButton("Enter Weight");
		panel_2.add(btnEnterWeight);
		
		btnPreferences = new JButton("Preferences");
		panel_2.add(btnPreferences);
		


		
		// setup the menus		
		menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		mnFile = new JMenu("File");
		menuBar.add(mnFile);
		
		mntmChangeUser = new JMenuItem("Change User");
		mnFile.add(mntmChangeUser);
		mntmChangeUser.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				btnChangeUser.doClick();
			}		
		});
		
		mntmExit = new JMenuItem("Exit");
		mnFile.add(mntmExit);
		mntmExit.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				btnClose.doClick();
			}			
		});
		
		mnPreferences = new JMenu("Preferences");
		menuBar.add(mnPreferences);
		
		mntmPreferences = new JMenuItem("Preferences");
		mntmPreferences.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				btnPreferences.doClick();
			}			
		});
		mnPreferences.add(mntmPreferences);
		
		mnChart = new JMenu("Chart");
		menuBar.add(mnChart);
		
		mntmChart = new JMenuItem("Chart");
		mntmChart.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				btnChart.doClick();
			}			
		});
		mnChart.add(mntmChart);
		
		mnHelp = new JMenu("Help");
		mnHelp.setHorizontalAlignment(SwingConstants.TRAILING);
		menuBar.add(mnHelp);
		
		mntmAbout = new JMenuItem("About");
		mntmAbout.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				
				// add the yawp icon
				BufferedImage myPicture = null;
				ImageIcon icon;
				try {
					URL imageURL = UserLoginWindow.class.getResource("images/yawp logo.jpg");
					myPicture = ImageIO.read(imageURL);
					icon = new ImageIcon( scale(myPicture, 150, 150));
					JOptionPane.showMessageDialog(null,
						    "<html>YAWP - Yet Another Weight Tracking Program. <br>Created as a BU Spring 2012 CS673 Class Project. <br>Please visit us at <a href=\"http://code.google.com/p/yawp\">http://code.google.com/p/yawp</a>",
						    "YAWP - About",
						    JOptionPane.INFORMATION_MESSAGE,
						    icon);
				} catch (IOException e1) {
					System.out.println("Could not find icon file: " + e1.getMessage());
				}				
			}			
		});
		mnHelp.add(mntmAbout);
			
		
		// set focus to the text field
		addWindowFocusListener(new WindowAdapter() {
		    public void windowGainedFocus(WindowEvent e) {
		        btnEnterWeight.requestFocusInWindow();
		    }
		} );

	}
	
	/**
	 *  hook for the view to register listener for Close Button
	 * @param listener
	 */
	public void setCloseActionListener(ActionListener listener) {
		btnClose.addActionListener(listener);
	}

	/**
	 * hook for the view to register listener for the New User Button
	 * @param listener
	 */
	public void setLoginActionListener(ActionListener listener) {
		btnChangeUser.addActionListener(listener);
	}

	/**
	 * hook for the view to register listener for the Chart Button
	 * @param listener
	 */
	public void setChartActionListener(ActionListener listener) {
		btnChart.addActionListener(listener);
	}

	/**
	 * hook for the view to register listener for the Add Weight Button
	 * @param listener
	 */
	public void setWeightEntryActionListener(ActionListener listener) {
		btnEnterWeight.addActionListener(listener);
	}

	/**
	 * hook for the view to register listener for the Add Weight Button
	 * @param listener
	 */
	public void setPreferencesActionListener(ActionListener listener) {
		btnPreferences.addActionListener(listener);
	}

	/**
	 * Observe changes in the model and update as needed
	 */
	@Override
	public void update(Observable o, Object arg) {
		// TODO Auto-generated method stub
		lblWelcome.setText(model.getUserName() + ", Welcome to YAWP!");
		System.out.println("Main Update!");
	}

	/**
	 *  Disconnect observer notifications
	 */
	private void unregister() {
		if (model != null) { 
			model.deleteObserver(this);
		}
	}
	
	/**
	 * WindowLister concrete method
	 * for System (Close) functionality
	 * after unregistering window as an observer
	 * @param e Close Window WindowEvent
	 */
	@Override
	public void windowClosing(WindowEvent e) {		
		unregister();
		btnClose.doClick();
	}

	/**
	 * WindowListner concrete method
	 */
	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * WindowListner concrete method
	 */
	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * WindowListner concrete method
	 */
	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * WindowListner concrete method
	 */
	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * WindowListner concrete method
	 */
	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * WindowListner concrete method
	 */
	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * Scale a buffered image
	 * copied forum example code from: http://www.coderanch.com/t/346438/GUI/java/Adjusting-image-size-image-label
	 * 
	 * Used to scale the yawp logo
	 * 
	 * @param src image to scale
	 * @param w width
	 * @param h hight
	 */
	private BufferedImage scale(BufferedImage src, int w, int h) {  
        int type = BufferedImage.TYPE_INT_RGB;  
        BufferedImage dst = new BufferedImage(w, h, type);  
        Graphics2D g2 = dst.createGraphics();  
        // Fill background for scale to fit.  
        g2.setBackground(UIManager.getColor("Panel.background"));  
        g2.clearRect(0,0,w,h);  
        double xScale = (double)w/src.getWidth();  
        double yScale = (double)h/src.getHeight();  
        // Scaling options:  
        // Scale to fit - image just fits in label.  
        double scale = Math.min(xScale, yScale);  
        // Scale to fill - image just fills label.  
        //double scale = Math.max(xScale, yScale);  
        int width  = (int)(scale*src.getWidth());  
        int height = (int)(scale*src.getHeight());  
        int x = (w - width)/2;  
        int y = (h - height)/2;  
        g2.drawImage(src, x, y, width, height, null);  
        g2.dispose();  
        return dst;  
    }  

}
